package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 添加菜品数据
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }


    /**
     * 菜品分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //1). 构造分页条件对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //2). 构建查询及排序条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //3). 执行分页条件查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝(page对象)
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        //4). 遍历分页查询列表数据，根据分类ID查询分类信息，从而获取该菜品的分类名称
        List<DishDto> list = records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);


        //5). 封装数据并返回
        return R.success(dishDtoPage);

    }

    /**
     * 根据id查询菜品信息(用于数据回显)
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getByIdWithFlavor(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品数据
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }


    /**
     * 根据分类id查询对应的菜品信息
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());

        queryWrapper.eq(Dish::getStatus,1);

        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);*/


    /**
     * 根据分类id查询对应的菜品信息
     * @param dish
     * @return
     */
        @GetMapping("/list")
        public R<List<DishDto>> list(Dish dish){
            //将dish类封装成dishdto类返回
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
            queryWrapper.eq(Dish::getStatus,1);
            queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
            List<Dish> list = dishService.list(queryWrapper);

            List<DishDto> dishDtos = list.stream().map((item)->{
                DishDto dishDto = new DishDto();
                //拷贝基本数据
                BeanUtils.copyProperties(item,dishDto);
                //存入分类名称
                Long categoryId = item.getCategoryId();
                Category category = categoryService.getById(categoryId);
                if (category != null){
                    String categoryName = category.getName();
                    dishDto.setCategoryName(categoryName);
                }
                
                //存入口味信息
                Long dishId = item.getId();
                LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
                List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);

                dishDto.setFlavors(dishFlavors);
                return dishDto;

            }).collect(Collectors.toList());

            return R.success(dishDtos);
    }


    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> remove(@RequestParam List<Long> ids){
            log.info("获取的ids: {}",ids);
            dishService.remove(ids);
            return R.success("删除成功");
    }

    /**
     * 修改菜品的起售停售
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@RequestParam List<Long> ids,@PathVariable Integer status){
        log.info("接收的状态: {}和id: {}",ids,status);
        //要停售的菜品的集合
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null,Dish::getId,ids);
        List<Dish> list = dishService.list(queryWrapper);


        for (Dish dish : list) {
         /*   Dish dish = dishService.getById(id);*/
            //停售操作
            if (status == 0){
                LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(SetmealDish::getDishId,dish.getId());
                List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper1);
                for (SetmealDish setmealDish : setmealDishes) {
                    LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Setmeal::getId,setmealDish.getSetmealId());
                    Setmeal setmeal = setmealService.getOne(wrapper);
                    if (setmeal.getStatus() == 1){
                        throw new CustomException("菜品关联的套餐为起售状态.无法设置菜品为停售状态");
                    }
                }
            }
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("修改成功");
    }
}
